<template>
  <div class="video-uploader">
    <!-- 上传区域（拖拽 + 点击选择） -->
    <div
        class="upload-area"
        @dragover.prevent="handleDragOver"
        @drop.prevent="handleDrop"
        @click="handleClickUpload"
        :class="{ 'upload-area-active': isDragging }"
    >
      <!-- 未选择文件时的提示 -->
      <div v-if="!videoFile" class="upload-hint">
        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#999" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <polygon points="21 15 13 23 5 15 5 5 13 13 21 5 21 15"></polygon>
          <path d="M17 10l-5 5-5-5"></path>
        </svg>
        <p>点击或拖拽视频文件到此处上传</p>
        <p class="upload-subhint">支持 MP4、WebM 等常见视频格式</p>
      </div>

      <!-- 已选择文件时的预览 -->
      <div v-else class="video-preview">
        <video
            :src="videoUrl"
            controls
            class="preview-video"
        ></video>
        <div class="video-info">
          <div>
            <p class="file-name">{{ videoFile.name }}</p>
            <p class="file-size">{{ formatFileSize(videoFile.size) }}</p>
          </div>
          <a-button size="small" danger @click.stop="removeVideo" :disabled="isUploading">移除文件</a-button>
        </div>
      </div>
    </div>

    <!-- 上传进度条和状态 -->
    <div v-if="isUploading" class="upload-progress">
      <a-progress :percent="uploadProgress" status="active" />
      <p class="progress-text">{{ uploadStatusText }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeUnmount, defineProps, defineEmits } from 'vue';
import { message } from 'ant-design-vue';
import SparkMD5 from 'spark-md5';
// 导入接口（与示例保持一致的导入方式）
import { checkFile, checkChunk, uploadChunk, mergeChunks } from '@/api/media/bizFilesController';

// 定义Props
const props = defineProps<{
  disabled?: boolean; // 是否禁用上传
}>();

// 定义事件
const emit = defineEmits<{
  (e: 'fileSelected', file: File): void;
  (e: 'uploadComplete', data: { fileMd5: string; fileName: string }): void;
  (e: 'uploadError', error: string): void;
  (e: 'fileRemoved'): void;
}>();

// 状态管理（与示例风格一致）
const videoFile = ref<File | null>(null);
const videoUrl = ref('');
const isDragging = ref(false);
const isUploading = ref(false);
const uploadProgress = ref(0);
const uploadStatusText = ref('准备上传...');
const fileMd5 = ref('');
const chunkSize = 5 * 1024 * 1024; // 5MB/块（与示例保持一致的分块大小）

// 处理拖拽悬停
const handleDragOver = (e: DragEvent) => {
  if (props.disabled) return;
  e.dataTransfer.dropEffect = 'copy';
  isDragging.value = true;
};

// 处理文件拖拽放下
const handleDrop = (e: DragEvent) => {
  if (props.disabled) return;
  isDragging.value = false;
  const files = e.dataTransfer?.files;
  if (files?.length) {
    handleVideoSelect(files[0]);
  }
};

// 点击选择文件
const handleClickUpload = () => {
  if (props.disabled) return;
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'video/*';
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (file) {
      handleVideoSelect(file);
    }
  };
  input.click();
};

// 处理选中的视频文件
const handleVideoSelect = (file: File) => {
  if (!file.type.startsWith('video/')) {
    message.error('请选择视频文件');
    return;
  }
  videoFile.value = file;
  videoUrl.value = URL.createObjectURL(file);
  emit('fileSelected', file);
  message.success(`已选择视频：${file.name}`);
  startUpload(); // 自动开始上传（与示例逻辑一致）
};

// 移除视频文件
const removeVideo = () => {
  if (videoUrl.value) {
    URL.revokeObjectURL(videoUrl.value);
    videoUrl.value = '';
  }
  videoFile.value = null;
  fileMd5.value = '';
  emit('fileRemoved');
};

// 格式化文件大小（与示例保持一致的格式）
const formatFileSize = (bytes: number): string => {
  if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  } else {
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }
};

// 计算文件MD5（核心逻辑与示例保持一致）
const calculateFileMD5 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const blobSlice = File.prototype.slice;
    const chunks = Math.ceil(file.size / chunkSize);
    let currentChunk = 0;
    const spark = new SparkMD5.ArrayBuffer();
    const fileReader = new FileReader();

    fileReader.onload = function(e) {
      spark.append(e.target?.result as ArrayBuffer);
      currentChunk++;

      // 更新进度文本（与示例一致的用户反馈）
      uploadStatusText.value = `正在计算文件校验值...(${currentChunk}/${chunks})`;

      if (currentChunk < chunks) {
        loadNextChunk();
      } else {
        resolve(spark.end());
      }
    };

    fileReader.onerror = function() {
      reject(new Error('文件读取失败'));
    };

    const loadNextChunk = () => {
      const start = currentChunk * chunkSize;
      const end = Math.min(start + chunkSize, file.size);
      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    };

    loadNextChunk();
  });
};

// 分块上传核心逻辑（按示例风格重构）
const startUpload = async () => {
  if (!videoFile.value || isUploading.value) return;

  isUploading.value = true;
  const file = videoFile.value;
  const chunkTotal = Math.ceil(file.size / chunkSize); // 与示例保持一致的参数名
  let uploadedChunks = 0;
  uploadProgress.value = 0;

  try {
    // 1. 计算文件MD5
    uploadStatusText.value = '正在计算文件校验值...';
    const fileMd5 = await calculateFileMD5(file);

    // 2. 检查文件是否已存在（可选）
    const fileCheckRes = await checkFile({ fileMd5 });
    if (fileCheckRes.data?.data) {
      message.success('文件已存在，无需重复上传');
      emit('uploadComplete', { fileMd5, fileName: file.name });
      isUploading.value = false;
      return;
    }

    // 3. 检查已上传分块（断点续传）
    uploadStatusText.value = '检查已上传分块...';
    const chunksToUpload: number[] = [];
    for (let chunk = 0; chunk < chunkTotal; chunk++) {
      const chunkCheckRes = await checkChunk({ fileMd5, chunk });
      if (!chunkCheckRes.data?.data) {
        chunksToUpload.push(chunk);
      } else {
        uploadedChunks++;
      }
    }
    uploadProgress.value = Math.floor((uploadedChunks / chunkTotal) * 100);

    // 4. 上传需要的分块（核心修复：传递file参数）
    if (chunksToUpload.length > 0) {
      uploadStatusText.value = `开始上传分块...(0/${chunksToUpload.length})`;

      for (const chunk of chunksToUpload) {
        const start = chunk * chunkSize;
        const end = Math.min(file.size, start + chunkSize);
        const chunkBlob = file.slice(start, end); // 当前分块的二进制数据

        // 构建FormData，严格匹配后端参数名：file、fileMd5、chunk
        const formData = new FormData();
        // 分块文件（键名必须为file，与后端@RequestParam("file")匹配）
        formData.append('file', chunkBlob, `chunk-${chunk}`);
        // 文件唯一标识（与后端fileMd5参数匹配）
        formData.append('fileMd5', fileMd5);
        // 分块序号（与后端chunk参数匹配）
        formData.append('chunk', chunk.toString());

        // 调用上传接口（传递formData，包含所有参数）
        const uploadRes = await uploadChunk(formData);
        if (uploadRes.code !== '00000') {
          throw new Error(`分块 ${chunk} 上传失败: ${uploadRes.message}`);
        }

        // 更新进度
        uploadedChunks++;
        uploadProgress.value = Math.floor((uploadedChunks / chunkTotal) * 100);
        uploadStatusText.value = `上传分块中...(${uploadedChunks}/${chunkTotal})`;
      }
    }
    // 5. 合并分块（与示例一致的合并流程）
    uploadStatusText.value = '正在合并文件...';
    const mergeRes = await mergeChunks({
      fileMd5: fileMd5,
      fileName: file.name,
      chunkTotal: chunkTotal // 使用与示例一致的参数名
    });

    if (mergeRes.code !== '00000') {
      throw new Error(`文件合并失败：${mergeRes.message || '未知错误'}`);
    }

    // 6. 上传完成
    uploadStatusText.value = '上传完成';
    uploadProgress.value = 100;
    emit('uploadComplete', {
      fileMd5: fileMd5,
      fileName: file.name
    });
    message.success('视频上传成功');

  } catch (error) {
    const errMsg = (error as Error).message || '上传失败';
    uploadStatusText.value = '上传失败';
    emit('uploadError', errMsg);
    message.error(errMsg);
  } finally {
    isUploading.value = false;
  }
};

// 组件卸载前释放资源
onBeforeUnmount(() => {
  if (videoUrl.value) {
    URL.revokeObjectURL(videoUrl.value);
  }
});

// 暴露方法给父组件
defineExpose({
  startUpload,
  clear: removeVideo
});
</script>

<style scoped>
/* 保持原有样式不变 */
.upload-area {
  width: 100%;
  min-height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-area-active {
  border-color: #1890ff;
  background-color: rgba(24, 144, 255, 0.05);
}

.upload-hint {
  text-align: center;
  color: #666;
}

.upload-hint p {
  margin: 8px 0 0;
  font-size: 14px;
}

.upload-subhint {
  font-size: 12px;
  color: #999;
  margin-top: 4px !important;
}

.video-preview {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-video {
  width: 100%;
  max-height: 300px;
  border-radius: 4px;
  object-fit: contain;
}

.video-info {
  width: 100%;
  margin-top: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-name {
  margin: 0;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 300px;
}

.file-size {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.upload-progress {
  margin-top: 16px;
}

.progress-text {
  margin: 8px 0 0;
  font-size: 12px;
  color: #666;
  text-align: center;
}
</style>
